<template>
  <div>
    <el-dialog append-to-body :title="dialogTitle" :visible="true"   class="relate-member" @close="close" width="950px" top="2vh">
      <el-row :gutter="20">
          <!-- <el-col :span="5">
              <div class="member-item">
                  <div class="member-label">{{title}}</div>
                  <div class="member-content">
                      <avue-tree
                          :option="treeOption"
                          :data="treeData"
                          @node-click="nodeClick">
                          <span class="el-tree-node__label" slot-scope="{ node, data }">
                          <el-tooltip class="item" effect="dark" content="无数据权限" placement="right-start" v-if="data.isLock">
                              <span>{{node.label}}  <i class="el-icon-lock"></i></span>
                          </el-tooltip>
                          <span v-if="!data.isLock">{{node.label}}</span>
                          </span>
                      </avue-tree>
                  </div>
              </div>
          </el-col> -->
          <el-col :span="24">
              <div class="member-item">
                  <!-- <div class="member-label">选择</div> -->
                  <div class="member-content">
                      <div class="search-block">
                           <a-input placeholder="请输入简称" v-model="pinyin"  v-if="title != '资产类别' && title != '组织机构' && title != '用品类别' && title != '药品类别'"/>
                           <a-input-search :placeholder="placeholder" v-model="namevalue" enter-button @search="onSearch" />
                           <avue-input-tree
                                    v-model="inputTreeValue"
                                    popperClass="cacacaaca" 
                                    :node-click="getType"
                                    :dic="treeData"
                                    :props="defaultProps"
                                    @change="changetree"
                                    :placeholder="placeholder1"/>
                            <!-- <el-cascader
                            @change="changeCategory"
                            :options="treeData"
                            :props="cProps"
                            clearable></el-cascader> -->
                      </div>
                      <a-table 
                          :row-key="delKey"
                          :columns="columns"
                          :scroll="{ y: 'calc(90vh - 358px)' }"
                          :data-source="allmemberList"
                          :row-selection="{selectedRowKeys: selectedRowKeys, type: 'checkbox', onChange: selectMembers, onSelect: onSelect, columnTitle:' ', type: type ? type : 'checkbox'}"
                          bordered
                          :pagination="page2"
                          :loading="loading"
                          @change="handleTableChange"
                      >
                      <template slot="deptId" slot-scope="text,record">
                          <span>
                          {{ record.deptName }}
                          </span>
                      </template>
                      <template slot="post" slot-scope="text,record">
                          <span>
                          {{ getPostName(record.post) }}
                          </span>
                      </template>
                      <template slot="cover" slot-scope="text,record">
                          <img :src="record.cover" alt="" height="50" @click="openPreview(record.cover)" style="cursor:pointer">
                      </template>
                      </a-table>
                    </div>
              </div>
          </el-col>
          <el-col :span="24" >
              <div class="member-item" v-if="code=='car_bill_apply'">
                  <div class="member-label">手工录入其他市局同乘人员
                  </div>
                    <el-tag
                        :key="tag"
                        v-for="tag in dynamicTags"
                        closable
                        :disable-transitions="false"
                        @close="handleClose(tag)">
                        {{tag}}
                    </el-tag>
                    <el-input
                        class="input-new-tag"
                        v-if="inputVisible"
                        v-model="inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm"
                        >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+添加</el-button>
              </div>
          </el-col>
          <el-col :span="24">
              <div class="member-item">
                  <div class="member-label">已选中
                      <el-button type="primary" style="float: right;margin: 2px 220px 0 0;" @click="dataSubmit">确 定</el-button>
                  </div>
                  <span class="chose-span">
                      <span v-for="item in newchosememberList">{{item}}</span>
                  </span>
              </div>
          </el-col>
          <!-- <el-col :span="6">
              <div class="member-item">
                  <div class="member-label">已选中</div>
                  <div class="member-content">
                      <a-table 
                          :row-key="delKey"
                          :columns="columns1"
                          :scroll="{ y: 'calc(90vh - 500px)' }"
                          :data-source="chosememberList"
                          bordered
                      >
                          <span slot="action" slot-scope="text, record">
                              <a @click="removeMember(record)">取消</a>
                          </span>
                      </a-table>
                  </div>
              </div>
              <div class="btn-footer">
                <el-button type="primary" @click="dataSubmit">确 定</el-button>
                <el-button @click="close">取 消</el-button>
            </div>
          </el-col> -->
      </el-row>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import { fetchList as fetchList1 } from '@/api/officegoods/officegoodscategory'
import { fetchList as fetchList3 } from '@/api/asset/assetcategory'
import { fetchList as fetchList2 } from '@/api/admin/sysposition'
import eventBus from '@/util/eventBus'
import request from '@/router/axios'
import _ from 'lodash'
export default {
  name: "chooseMember",
  props: ['labelkey', 'url1', 'url2', 'title', 'columns1', 'columns', 'limitLabel', 'type', 'flKey', 'validClose', 'chosedKey', 'choselist','code'],
  data () {
    return {
      pinyin: '',
      page2: {
          total: 0, // 总页数
          current: 1, // 当前页数
          pageSize: 20, // 每页显示多少条,
          isAsc: false// 是否倒序
      },
      namevalue: '',
      inputTreeValue: '',
      newchosememberList: [],
      placeholder: '请输入姓名',
      placeholder1: '请选择部门',
      dialogTitle: '添加成员',
      cProps: {
        label: 'name',
        value: 'id',
        emitPath:false,
        checkStrictly: true
      },
       defaultProps: {
            label: 'name',
            value: 'id'
        },
      loading: false,
      delKey: 'userId',
      categoryData: '',
      treeOption: {
          nodeKey: 'id',
          addBtn: false,
          defaultExpandAll:true,
          menu: false,
          props: {
              label: 'name',
              value: 'id'
          }
      },
      flList: [],
      lbList: [],
      postList: [],
      selectedRowKeys: [],
      allmemberList: [],
      chosememberList:[],
      treeData: [],
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
    }
  },
  created() {
    if(this.chosedKey && this.chosedKey.length > 0) {
        this.selectedRowKeys = Object.assign([], this.chosedKey)
    }
    if (this.choselist && typeof(this.choselist) == 'object' && this.choselist.length > 0) {
        this.chosememberList =  this.choselist
        this.newchosememberList = this.chosememberList.map(item => {
            return item[this.columns1[0].key]
        })
        if(this.code =='car_bill_apply'){
            //过滤外部人员展示
            let filterTags = this.chosememberList.filter(item => {
                    return item.personType == 'external'
                })
            this.dynamicTags = filterTags?.map(item => {
                return item[this.columns1[0].key]
            })
        }
        
    }
    this.init()
    if (this.flKey == 'deptId') {
        this.inputTreeValue = _.get(this, '$store.getters.userInfo.deptId')
        this.getmemberList(this.page2, {deptId: this.inputTreeValue})
    } else {
        this.getmemberList(this.page2)
    }
    
  },
  methods: {
    handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        this.chosememberList = this.chosememberList.filter(item => {
                return item[this.columns1[0].key] !== tag
            })
        this.newchosememberList = this.chosememberList.map(item => {
            return item[this.columns1[0].key]
        })
    },

    showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
        });
    },

    handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
            this.dynamicTags.push(inputValue);

            this.chosememberList.push({
                "realname":inputValue,
                "personType":"external"
            })
            this.newchosememberList.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
    },
    changetree(value) {
        if (!value) {
            this.page2.current = 1
            let params = {}
            params[this.flKey] = ''
            if (this.pinyin) {
                params['pinyin'] = this.pinyin
            } else {
                params['pinyin'] = ''
            }
            if (this.namevalue) {
                if (this.title === '组织机构') {
                    params['realname'] = this.namevalue
                } else {
                    params['name'] = this.namevalue
                }
            }
            this.getmemberList(this.page2, params)
        }
    },
    changeCategory(val) {
        this.page2.current = 1
        let params = {}
        params[this.flKey] = val
        this.getmemberList(this.page2, params)
    },
    getType(data) {
        this.page2.current = 1
        let params = {}
        if (this.pinyin) {
            params['pinyin'] = this.pinyin
        } else {
            params['pinyin'] = ''
        }
        if (this.namevalue) {
           if (this.title === '组织机构') {
                params['realname'] = this.namevalue
            } else {
                params['name'] = this.namevalue
            }
        }
        params[this.flKey] = data.id
        this.getmemberList(this.page2, params)
    },
    openPreview(img) {
        let list = [
            {
                thumbUrl: img,
                url: img
            }
        ]
        this.$ImagePreview(list, 0,{
            closeOnClickModal: true,
            beforeClose:()=>{
            }
        })
    },
    dataSubmit() {
      let namelist = []
      let valueList = []
      let userList = []
      this.chosememberList.map(item => {
        if (this.title === '组织机构') {
            namelist.push(item.realname)
        }
        // 维保
        if (this.limitLabel === '添加资产') {
            valueList.push(item.assetId)
        }
        userList.push(item)
      })
      let obj = {}
      let labelstr = this.labelkey.split('_choose_member')[0]
      if (this.title === '组织机构') {
        obj[this.labelkey] = namelist.join()
        obj[labelstr] = userList
      } else {
        obj[this.labelkey] = userList
      }
      obj.choselist = Object.assign([], userList)
      obj.chosedKey = Object.assign([], this.selectedRowKeys)
      // 维保
      if (this.limitLabel === '添加资产') {
        obj[labelstr] = valueList
      }
      let obj1 = Object.assign({}, obj)
      console.log("obj1",obj1)
      eventBus.$emit('getMember', obj1)
      if (!this.validClose) {// 是否父页面控制关闭窗口
          this.close()
      }
    },
    onSearch(val) {
        let att = {}
        if (this.title === '组织机构') {
            att['realname'] = val
        } else {
            att['name'] = val
        }
        if (this.pinyin) {
            att['pinyin'] = this.pinyin
        } else {
            att['pinyin'] = ''
        }
        att[this.flKey] = this.inputTreeValue
        this.page2.current = 1
        this.getmemberList(this.page2, att)
    },
    close() {
      this.$parent.showChose = false
    },
    handleTableChange(pagination, filters, sorter) {
        this.page2.current = pagination.current
        let params = {}
        if (this.pinyin) {
            params['pinyin'] = this.pinyin
        } else {
            params['pinyin'] = ''
        }
        if (this.namevalue) {
           if (this.title === '组织机构') {
                params['realname'] = this.namevalue
            } else {
                params['name'] = this.namevalue
            }
        }
        params[this.flKey] = this.inputTreeValue
        this.getmemberList(this.page2, params)
    },
    selectMembers(selectedRowKeys, selectedRows) {
        if (this.limitLabel && this.chosememberList.length === 5) {
            if (this.limitLabel === '药品名称【请选择(个人领药)+】') {
                this.$message.error('个人领药每次只能领取五种药品')
            } else if (this.limitLabel === '药品名称【请选择(老干领药)+】') {
                this.$message.error('老干领药每次只能领取五种药品')
            } else {
                this.selectedRowKeys = Object.assign([], selectedRowKeys)
            }
        } else {
            this.selectedRowKeys = Object.assign([], selectedRowKeys)
        }
    },
    onSelect(record, selected, selectedRows, nativeEvent) {
        if (selected) {
             if (this.limitLabel && (this.limitLabel === '药品名称【请选择(个人领药)+】' || this.limitLabel === '药品名称【请选择(老干领药)+】') && this.chosememberList.length === 5) {
             } else {
                if (this.type === 'radio') {
                    this.chosememberList = Object.assign([], selectedRows)
                } else {
                    let a = Object.assign([], this.chosememberList)
                    // 2023/05/21 新增内部人员internal和外部人员标识external
                    if(this.code =='car_bill_apply'){
                        record.personType = 'internal'
                    }
                    a.push(record)
                    this.chosememberList =  Object.assign([], a)
                }
             }
        } else {
            this.chosememberList = this.chosememberList.filter(item => {
                return item[this.delKey] !== record[this.delKey]
            })
            this.selectedRowKeys = selectedRows.map(item => {
                return item[this.delKey]
            })
        }
        this.newchosememberList = this.chosememberList.map(item => {
            return item[this.columns1[0].key]
        })
    },
    removeMember(record) {
        this.chosememberList = this.chosememberList.filter(item => {
            return item[this.delKey] !== record[this.delKey]
        })
        this.newchosememberList = this.chosememberList.map(item => {
            return item[this.columns1[0].key]
        })
        let alist = []
        this.selectedRowKeys.map(item => {
            if(item !== record[this.delKey]) {
                alist.push(item)
            }
        })
        this.selectedRowKeys = alist
    },
    init() {
        request({
            url: this.url1,
            method: 'get',
            params: {}
        }).then(response => {
            this.treeData = response.data.data
        })
        if (this.title === '组织机构') {
            this.dialogTitle = '添加成员'
            this.placeholder = '请输入姓名'
            this.placeholder1 = '请选择所属部门'
            this.delKey = 'userId'
        } else if (this.title === '药品类别') {
            this.dialogTitle = '添加药品'
            this.placeholder = '请输入药品名称'
            this.placeholder1 = '请选择药品类别'
            this.delKey = 'drugId'
        } else if (this.title === '用品类别') {
            this.placeholder = '请输入用品名称'
            this.dialogTitle = '添加用品'
            this.placeholder1 = '请选择用品类别'
            this.delKey = 'officegoodsId'
        } else if (this.title === '资产类别') {
            this.placeholder = '请输入资产名称'
            this.placeholder1 = '请选择资产类别'
            this.dialogTitle = '选择'
            this.delKey = 'assetId'
        }
        fetchList1({current: 1, size:1000}).then(response => {
            this.flList = response.data.data.records
        })
        fetchList2({current: 1, size:1000}).then(response => {
            this.postList = response.data.data.records
        })
        fetchList3({current: 1, size:1000}).then(response => {
            this.lbList = response.data.data.records
        })
    },
    // nodeClick(data) {
    //     this.page2.current = 1
    //     let params = {}
    //     params[this.flKey] = data.id
    //     this.getmemberList(this.page2, params)
    // },
    getFlName(id) {
        let list =  this.flList.filter(item => {
            return item.categoryId === id
        })
        return list.length > 0 ? list[0].name : ''
    },
    getFlParentId(id) {
        let list =  this.flList.filter(item => {
            return item.categoryId === id
        })
        return list.length > 0 ? list[0].parentId : ''
    },
    getLbName(id) {
        let list =  this.lbList.filter(item => {
            return item.categoryId === id
        })
        return list.length > 0 ? list[0].name : ''
    },
    getPostName(id) {
        let list =  this.postList.filter(item => {
            return item.id === id
        })
        return list.length > 0 ? list[0].name : ''
    },
    // 获取部门人员列表
    getmemberList(page, params) {
        let pObj = {
            current: page.current,
            size: page.pageSize
        }
        let _this = this
        if (this.flKey === 'categoryId'){
            if(this.limitLabel === '维修资产【请选择+】' || this.limitLabel === '清理资产【请选择+】' || this.limitLabel === '变更资产【请选择+】') {
                 pObj.bizStatus = '0'
            } else if(this.limitLabel === '变动资产【请选择+】') {
                pObj.bizStatus = '0'
                pObj.useId = _.get(this, '$store.getters.userInfo.userId')
            } else if(this.limitLabel === '采购资产【请选择+】') {
            } else if(this.limitLabel === '资产名称【请选择+】' || this.limitLabel === '借用资产【请选择+】') {
                 pObj.status = '0' // 闲置
                 pObj.bizStatus = '0'
            } else if(this.limitLabel === '退库资产【请选择+】') {
                 pObj.status = '1' // 在用
                 pObj.bizStatus = '0'
                 pObj.useId = _.get(this, '$store.getters.userInfo.userId')
            } else if(this.limitLabel === '添加资产') {
                pObj.statuses = '0, 1, 2'
            } else if(this.limitLabel === '采购用品名称【请选择+】') {
                pObj.areaId = _.get(this, '$store.getters.userInfo.rootAreaId')
            } else {
                pObj.status = '1'
                pObj.areaId = _.get(this, '$store.getters.userInfo.rootAreaId')
            }
        }
        // if (this.flKey === 'deptId') {
        //     pObj.deptId =  _.get(this, '$store.getters.userInfo.deptId')
        // }
        request({
            url: this.url2,
            method: "get",
            params: Object.assign(pObj, params)
        }).then(response => {
            let list = []
            response.data.data.records.map(item => {
                if (item.officegoodsId && item.categoryId) {
                    item.categoryName = this.getFlName(item.categoryId)
                    //新增返回采购用品大类类别
                    item.categoryParentId = this.getFlParentId(item.categoryId)
                }
                if (item.assetId && item.categoryId) {
                    item.categoryName = this.getLbName(item.categoryId)
                }
                // if (this.selectedRowKeys.length > 0) {
                //     this.selectedRowKeys.map(citem => {
                //         if (citem == item[_this.delKey]) {
                //             list.push(item)
                //         }
                //     })
                //     this.chosememberList = Object.assign(this.chosememberList, list)
                // }
            })
            this.allmemberList = response.data.data.records
            this.page2.total = response.data.data.total
        })
    },
  }
}
</script>

<style lang="scss">
.relate-member{
    margin-bottom: 0;
    .el-dialog{
        height: 96%;
        .el-dialog__headerbtn{
            top: 5px;
        }
        .el-dialog__title{
            display: none;
        }
        .el-dialog__body{
            padding: 0 20px;
        }
    }
    .chose-span{
        font-size: 15px;
        word-break: break-word;
        line-height: 1.5;
        display: inline-block;
        height: 70px;
        overflow-y: auto;
        padding-left: 20px;
        span{
            margin-right: 20px;
            display: inline-block;
        }
    }
    .member-item{
        border:1px solid #e8e8e8;
        .member-label{
            height:40px;
            font-size: 15px;
            line-height: 40px;
            padding-left: 20px;
            border-bottom: 1px solid #e8e8e8;
        }
        .member-content{
            padding: 20px;
            padding-bottom: 0;
            .el-tree{
                // height: calc(90vh - 280px);
                height: calc(90vh - 250px);
                overflow: auto;
            }
            .search-block{
                .ant-input{
                    width: 250px;
                    height: 32px;
                    font-size: 15px;
                }
                .el-cascader, .avue-input-tree{
                    width: 250px;
                    margin-left: 50px;
                }
                .ant-input-search{
                    // margin-left: 10px;
                    width: 250px;
                    margin-bottom: 10px;
                    
                }
            }
        }
    }
    .btn-footer{
        text-align: center;
        margin-top: 30px;
        text-align: center;
    }
}
.el-select-dropdown__wrap{
    max-height: 500px;
}
.ant-table-thead > tr > th, .ant-table-tbody > tr > td{
    padding: 10px;
}
.ant-table-row-cell-break-word{
    img{
        height: 30px;
    }
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
